package com.ssd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssd.entity.PointsRecord;
import com.ssd.entity.PointsRecordTotal;
import com.ssd.entity.dto.request.PointsRecordTotalPageReqDTO;
import com.ssd.entity.dto.response.PointsRecordPageInfoResDTO;
import com.ssd.exception.LogicException;
import com.ssd.mapper.PointsRecordTotalMapper;
import com.ssd.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssd.service.IPointsRecordTotalService;
import com.ssd.utils.DateUtils;
import com.ssd.utils.IdUtils;
import com.ssd.utils.UserContext;
import com.ssd.viewmodel.Pager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 积分总表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-21
 */
@Service
public class PointsRecordTotalServiceImpl extends ServiceImpl<PointsRecordTotalMapper, PointsRecordTotal> implements IPointsRecordTotalService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IPointsRecordService pointsRecordService;

    /**
     * 生成积分记录id 格式：{yyMMdd}{13位id} TODO
     * @return
     */
    public   Long generatorPointsRecordId() {
        //通过Redis自增序列得到序号
        Long id = redisTemplate.opsForValue().increment("pointsRecord:page_key:generator", 1);
        long pointsRecordId = DateUtils.getFormatDate(LocalDateTime.now(), "yyMMdd") * 10000000000000L + id;
        return pointsRecordId;
    }

    @Override
    public Integer getPointsRecordTotal() {
        //1.用户信息
        Long userId = UserContext.currentUserId();
        //2.查询并返回
        return lambdaQuery()
                .eq(PointsRecordTotal::getUserId, userId)
                .one()
                .getPoints();
    }

    @Override
    public List<PointsRecordPageInfoResDTO> queryPointsRecordForPage(Long lastId, Integer status) {
        //1.获取用户id
        Long userId = UserContext.currentUserId();
        //2.设置查询条件
        List<PointsRecord> list = pointsRecordService
                .lambdaQuery()
                .eq(PointsRecord::getUserId, userId)
                .eq(ObjectUtil.isNotNull(status), PointsRecord::getType, status)
                .le(ObjectUtil.isNotNull(lastId), PointsRecord::getId, lastId)
                .orderByDesc(PointsRecord::getId)
                .last(" limit 10")
                .list();
        if (CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        //3.获取积分记录id集合
        List<Long> longs = list.stream().map(PointsRecord::getId).collect(Collectors.toList());
        //4.查询数据库
        List<PointsRecord> pointsRecords = pointsRecordService.getBaseMapper().selectBatchIds(longs).stream()
                .sorted(Comparator.comparing(PointsRecord::getCreateTime).reversed())
                .collect(Collectors.toList());
        return BeanUtil.copyToList(pointsRecords, PointsRecordPageInfoResDTO.class);
    }

    @Override
    public void saveUserPointsRecordTotal(Long userId) {
        PointsRecordTotal pointsRecordTotal=new PointsRecordTotal();
        pointsRecordTotal.setId(IdUtils.getSnowflake().nextId());
        pointsRecordTotal.setUserId(userId);
        pointsRecordTotal.setPoints(0);
        if (!save(pointsRecordTotal)){
            throw new LogicException("创建积分表失败！");
        }
    }

    @Override
    public Pager<PointsRecordTotal> selectPointsRecordTotalList(PointsRecordTotalPageReqDTO pointsRecordTotalPageReqDTO) {
        //设置分页参数
        Page<PointsRecordTotal> page=new Page<>(pointsRecordTotalPageReqDTO.getPageNo(),pointsRecordTotalPageReqDTO.getPageSize());
        // 分页查询
        Page<PointsRecordTotal> pointsRecordTotalPage = lambdaQuery()
                .eq(ObjectUtil.isNotNull(pointsRecordTotalPageReqDTO.getId()), PointsRecordTotal::getId, pointsRecordTotalPageReqDTO.getId())
                .eq(ObjectUtil.isNotNull(pointsRecordTotalPageReqDTO.getUserId()), PointsRecordTotal::getUserId, pointsRecordTotalPageReqDTO.getUserId())
                .orderByDesc(PointsRecordTotal::getCreateTime)
                .page(page);
        //返回分页数据
        if (pointsRecordTotalPage == null){
            return Pager.buildEmpty();
        }

        return Pager.build(pointsRecordTotalPage);
    }

    @Override
    public void deletePointsRecordTotalByIds(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        boolean flag = removeByIds(list);
        if (!flag){
            throw new LogicException("删除失败！");
        }
    }

}
